#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include "../common/Argv.h"
#include "../common/ArchivoIni.h"
#include "../common/StringUtils.h"
#include "../logger/logger.h"
#include "../IPC/ClientSocket.h"
#include "../channel_common/ChannelInterface.h"
#include "../channel_common/ChannelCommon.h"
#include "../middleware/CommunicationVendedor.h"

int main(int argc, char **argv)
{
	try
	{
		//Toma argumentos (main)
		Argv args(argv);

		if (args.getArgc() != 2)
		{
			std::cout <<"Canal entrada agente: Cantidad de parametros invalida: "<<
						 StringUtils::NumberToString(args.getArgc())<<std::endl;
			exit(1);
		}

		std::string server;
		int puertoSalida = 0;
		std::string hostName = args.getArg(1);

		CLogger::create("Canal entrada host:"+hostName);

		//Obtengo la configuracion
		MapaIni config = ArchivoIni::parsearComoIni("config.ini");

		server = config["server_vend"];
		puertoSalida = StringUtils::StringToNumber<int>(config["puerto_salida_vend"]);

		CLogger::log("El host:"+ hostName+" se conecto a:"+server+":"+
					  StringUtils::NumberToString(puertoSalida),
					  LogLevelEnum::INFO);

		//Construccion IPCs
		ipc::ClientSocket socketEntrada;
		socketEntrada.connect(server, puertoSalida);

		channel::ChannelInterface queue(channel::ChannelInterface::RECEIVER,hostName);


		//----Aviso de mi hostname
		channel::StartComunicationMessage startMsg;
		char buffer[TAM_BUFFER];

		strcpy(startMsg.channelName,hostName.c_str());

		memcpy(buffer,&startMsg,sizeof(startMsg));

		socketEntrada.send(buffer,TAM_BUFFER);

		//Ciclo principal (run)
		bool deboSeguir = true;
		channel::ChannelMessage netMsg;

		while (deboSeguir)
		{
			socketEntrada.receive(buffer,TAM_BUFFER);

			memcpy(&netMsg, buffer,	sizeof(channel::ChannelMessage));

			CLogger::log("Obtuve un mensaje para:"+
					StringUtils::NumberToString(netMsg.destino)+
					" de tamaño:"+StringUtils::NumberToString(netMsg.size)+
					" y contenido"+StringUtils::toHexaString(netMsg.payload,netMsg.size));

			if (netMsg.tipo == channel::CHANNEL_END_MSG)
				deboSeguir = false;
			else
				queue.putInQueue(netMsg);
		}

		socketEntrada.close();

		CLogger::log("Canal Entrada Agente - Finalizando.",LogLevelEnum::INFO);
	}
	catch (Exception &e)
	{
		CLogger::log("Excepcion:"+e.what_str(),LogLevelEnum::FATAL);
		exit(1);
	}
}
